package com.mini.common;

import com.mini.common.util.JacksonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author 小鱼儿
 * @date 2020/11/17 18:21
 */
@Service
public class RedisService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    public <T> T hget(String key, String item, Class<T> cls) {
        String ret = (String) hget(key, item);
        if (ret == null) {
            return null;
        }
        return JacksonUtil.stringToBean(ret, cls);
    }

    public String get(String key) {
        return (String) redisTemplate.opsForValue().get(key);
    }

    public long getLong(String key){
        String value = (String)redisTemplate.opsForValue().get(key);
        if(value == null){
            return 0;
        }
        return Long.parseLong(value);
    }

    public void set(String key, String value, long time) {
        redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
    }

    public void hset(String key, String key2,String value) {
        redisTemplate.opsForHash().put(key,key2,value);
    }

    public void expire(String key, long time){
        redisTemplate.expire(key, time, TimeUnit.SECONDS);
    }

    public long incr(String key, int delta) {
        return redisTemplate.opsForValue().increment(key, delta);
    }

    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }
}
